# _*_ coding:utf-8 _*_
# @Time  : 2022.11.28
# @Author: zizlee

__all__ = ['MSSQLProxy']

import pymssql
import datetime
from dbutils.pooled_db import PooledDB, PooledSharedDBConnection
# 10.100.56.11,8866
#  zhenduan/zhenduan
MSSQL_CONFIG = {
    'server': '59.57.33.15',
    'port': '53200',
    'user': 'qth',
    'password': 'qth565656',
    'database': 'jsd_data',
    'charset': 'utf8',
    'as_dict': True
}

# 创建连接池
ms_db_pool: PooledDB = PooledDB(
    creator=pymssql, mincached=5, maxcached=10,
    blocking=True,
    **MSSQL_CONFIG
)


# 使用连接池
class MSSQLProxy(object):
    def __init__(self, request_action: str = 'Unknown'):
        self.request_action = request_action
        self.conn: PooledSharedDBConnection = ms_db_pool.connection()  # 从连接池取得一个连接
        self.cursor: pymssql.Cursor = self.conn.cursor()  # 连接的游标

    def begin(self):
        self.conn.begin()
        print(str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')), 'MSSQL Begin...')

    def close(self):
        self.cursor.close()
        self.conn.close()
        print(str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')), 'MSSQL Closed!')

    def commit(self):
        self.conn.commit()

    def rollback(self):
        self.conn.rollback()

    def __enter__(self):
        self.begin()
        return self.cursor

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            self.rollback()
            print(f'MSSQL { self.request_action } Error:{ exc_type.__name__ }:{ exc_val }')
        else:
            self.commit()
        self.close()
